package com.epfresh.api.ucrop;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v4.content.res.ResourcesCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.epfresh.api.R;
import com.epfresh.api.entity.RequestEntity;
import com.epfresh.api.global.AppActivity;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.permission.HiPermission;
import com.epfresh.api.permission.PermissionCallback;
import com.epfresh.api.permission.PermissonItem;
import com.epfresh.api.ucrop.task.BitmapProcessTask;
import com.epfresh.api.utils.FileUtil;
import com.epfresh.api.utils.L;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.api.utils.T;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wzh on 2016/4/13.
 */
public class PhotoCore implements View.OnClickListener {
    public int listPosition;

    public int getListPosition() {
        return listPosition;
    }

    public void setListPosition(int listPosition) {
        this.listPosition = listPosition;
    }

    public static final int REQUEST_CAMERA_CROP_CODE = 1991;
    public static final int REQUEST_CAMERA = 1992;
    //调用系统相机的Code
    public static final int REQUEST_TAKE_PHOTO_CODE = 1001;
    //拍照裁剪的Code
    public static final int REQUEST_TAKE_PHOTO_CROP_CODE = 1003;
    //调用系统图库的Code
    public static final int REQUEST_TAKE_PICTRUE_CODE = 1002;
    //调用系统图库裁剪Code
    public static final int REQUEST_TAKE_PICTRUE_CROP_CODE = 1004;
    //裁剪的Code
    public static final int REQUEST_TAKE_CROP_CODE = 1005;
    //截取图片的高度
    public static final int REQUEST_HEIGHT = 400;
    //截取图片的宽度
    public static final int REQUEST_WIDTH = 400;


    //用来存储照片的URL
    private Uri photoURL;
    private String photoURLPath;


    //调用照片的Activity
    private AppActivity activity;

    //回调函数
    private PhotoResult cameraResult;

    private Dialog dialog;

    private int resultWidth = 512;
    private int resultHeight = 512;
    private int ratioX = 1;
    private int ratioY = 1;
    private boolean isCrop = true;
    DialogInterface.OnDismissListener listener;

    public PhotoCore(PhotoResult cameraResult, AppActivity activity) {
        this.cameraResult = cameraResult;
        this.activity = activity;
    }

    public void setOnDismissListener(DialogInterface.OnDismissListener listener) {
        this.listener = listener;
        if (dialog != null)
            dialog.setOnDismissListener(listener);
    }

    public boolean isCrop() {
        return isCrop;
    }

    public void setCrop(boolean crop) {
        isCrop = crop;
    }

    public Uri getPhotoURL() {
        return photoURL;
    }

    public void setPhotoURL(Uri photoURL) {
        this.photoURL = photoURL;
    }

    public int getResultWidth() {
        return resultWidth;
    }

    public void setResultWidth(int resultWidth) {
        this.resultWidth = resultWidth;
    }

    public int getResultHeight() {
        return resultHeight;
    }

    public void setResultHeight(int resultHeight) {
        this.resultHeight = resultHeight;
    }

    public int getRatioX() {
        return ratioX;
    }

    public void setRatioX(int ratioX) {
        this.ratioX = ratioX;
    }

    public int getRatioY() {
        return ratioY;
    }

    public void setRatioY(int ratioY) {
        this.ratioY = ratioY;
    }

    public void setRatio(int x, int y) {
        this.ratioX = x;
        this.ratioY = y;
    }

    @Override
    public void onClick(View v) {
        if (dialog != null)
            dialog.dismiss();
        int id = v.getId();

        if (id == R.id.tv_take_photo) {
            if (isCrop) {
                getPhoto2CameraCrop(photoURL);
            } else {
                getPhoto2Camera(photoURL);

            }
        } else if (id == R.id.tv_get_photo) {
            if (isCrop) {
                getPhoto2AlbumCrop(photoURL);
            } else {
                getPhoto2Album(photoURL);
            }
        } else if (id == R.id.tv_upload) {
            cameraResult.onReupload();
        } else if (id == R.id.tv_cancel) {

        }


    }

    private View vReupload;

    public void showPhotoDialog(final Uri photoURL, final String filePath, final boolean isReupload) {
        HiPermission.create(activity)
                .checkMutiPermission(new PermissionCallback() {
                    @Override
                    public void onClose() {
                       T.toast("取消");
                    }

                    @Override
                    public void onFinish() {
                        showDialog(photoURL,filePath,isReupload);
                    }

                    @Override
                    public void onDeny(String permisson, int position) {

                    }

                    @Override
                    public void onGuarantee(String permisson, int position) {
                       showDialog(photoURL,filePath,isReupload);
                    }
                });


    }

    public void showDialog(Uri photoURL, String filePath,boolean isReupload) {
        Log.e("该图片-photoURL","_"+photoURL+"filePath:"+filePath);
        this.photoURL = photoURL;
        this.photoURLPath = filePath;
        if (dialog == null) {
            View view = LayoutInflater.from(activity).inflate(R.layout.dialog_photos, null);
            vReupload = view.findViewById(R.id.tv_upload);
            vReupload.setOnClickListener(this);
            view.findViewById(R.id.tv_take_photo).setOnClickListener(this);
            view.findViewById(R.id.tv_get_photo).setOnClickListener(this);
            view.findViewById(R.id.tv_cancel).setOnClickListener(this);
            dialog = new Dialog(activity, R.style.ActionSheetDialogStyle);
            dialog.setContentView(view);
            Window dialogWindow = dialog.getWindow();
            dialogWindow.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            lp.width = LocalDisplay.SCREEN_WIDTH_PIXELS;
            dialogWindow.setAttributes(lp);
            dialog.setOnDismissListener(listener);
        }
        if (isReupload) {
            vReupload.setVisibility(View.VISIBLE);
        } else {
            vReupload.setVisibility(View.GONE);
        }
        dialog.show();
    }

    //调用系统照相机，对Intent参数进行封装
    protected Intent startTakePhoto(Uri photoURL) {
        this.photoURL = photoURL;


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

            File newFile = new File(photoURLPath);
            Uri contentUri = FileProvider.getUriForFile(activity,
                    ApplicationHelper.getInstance().getFileProvider(), newFile);
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
            // 授予目录临时共享权限
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
                    | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

            return intent;
        }else {
            Intent intent = new Intent();
            intent.putExtra("camerasensortype", 2);
            intent.putExtra("autofocus", true);
            intent.putExtra("fullScreen", false);
            intent.putExtra("showActionIcons", false);
            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//设置Action为拍照
            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURL);//将拍取的照片保存到指定URI
            return intent;
        }



        /* /*//***************************************************************//*/
            // 重新构造Uri：content://
            File imagePath = new File(Context.getFilesDir(), "images");
            if (!imagePath.exists()){imagePath.mkdirs();}
            File newFile = new File(imagePath, "default_image.jpg");
            Uri contentUri = getUriForFile(getContext(),
                    "com.mydomain.fileprovider", newFile);
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
            // 授予目录临时共享权限
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
                    | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            startActivityForResult(intent, 100);
            /*//***************************************************************//*/*/
    }


    //调用系统图库,对Intent参数进行封装
    protected Intent startTakePicture(Uri photoURL) {
        this.photoURL = photoURL;
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        intent.setType("image/*");//从所有图片中进行选择
        return intent;
    }


    //调用系统裁剪图片，对Intent参数进行封装
    protected Intent takeCropPicture(Uri photoURL, int with, int height) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(photoURL, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", with);
        intent.putExtra("outputY", height);
        intent.putExtra("scale", true);
        intent.putExtra("scaleUpIfNeeded", true);//黑边
        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURL);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        return intent;
    }


    //拍照
    public void getPhoto2Camera(Uri uri) {
        if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            // Check Permissions Now
            // Callback onRequestPermissionsResult interceptado na Activity MainActivity
            ActivityCompat.requestPermissions(activity,
                    new String[]{Manifest.permission.CAMERA},
                    REQUEST_CAMERA);
        } else {
            activity.startActivityForResult(startTakePhoto(uri), REQUEST_TAKE_PHOTO_CODE);
        }
    }

    //拍照后截屏
    public void getPhoto2CameraCrop(Uri uri) {
        if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            // Check Permissions Now
            // Callback onRequestPermissionsResult interceptado na Activity MainActivity
            ActivityCompat.requestPermissions(activity,
                    new String[]{Manifest.permission.CAMERA},
                    REQUEST_CAMERA_CROP_CODE);
        } else {
            Intent intent = startTakePhoto(uri);
            // intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);//将拍取的照片保存到指定URI
            activity.startActivityForResult(intent, REQUEST_TAKE_PHOTO_CROP_CODE);

        }
    }


    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CAMERA: {
                // If requestSilent is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    activity.startActivityForResult(startTakePhoto(photoURL), REQUEST_TAKE_PHOTO_CODE);

                } else {
                    T.toast("相机获取权限失败");
                }
                return;
            }
            case REQUEST_CAMERA_CROP_CODE: {
                // If requestSilent is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Intent intent = startTakePhoto(photoURL);
                    // intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);//将拍取的照片保存到指定URI
                    activity.startActivityForResult(intent, REQUEST_TAKE_PHOTO_CROP_CODE);
                } else {
                    T.toast("相机获取权限失败");
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might requestSilent
        }
    }

    //获取系统相册
    public void getPhoto2Album(Uri uri) {
        activity.startActivityForResult(startTakePicture(uri), REQUEST_TAKE_PICTRUE_CODE);
    }

    //获取系统相册后裁剪
    public void getPhoto2AlbumCrop(Uri uri) {
        activity.startActivityForResult(startTakePicture(uri), REQUEST_TAKE_PICTRUE_CROP_CODE);
    }

    public void onCropPic(Uri source, Uri destination) {
        UCrop uCrop = UCrop.of(source, destination);
        uCrop.withAspectRatio(ratioX, ratioY);
        uCrop.withMaxResultSize(resultWidth, resultHeight);
        UCrop.Options options = new UCrop.Options();
        options.setCompressionFormat(Bitmap.CompressFormat.JPEG);
        options.setCompressionQuality(100);
//        options.setMaxBitmapSize(512*512);
        options.setHideBottomControls(true);
        uCrop.withOptions(options);

        uCrop.start(activity);

    }


    //处理onActivityResult
    public void onResult(int requestCode, int resultCode, Intent intent) {
        L.e("adsafsdafsadf", "requestCode:" + requestCode);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                //选择系统图库
                case REQUEST_TAKE_PICTRUE_CODE:
                    //获取系统返回的照片的Uri
//                    photoURL = intent.getData();
//                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
//                    //从系统表中查询指定Uri对应的照片
//                    Cursor cursor = activity.getContentResolver().query(photoURL, filePathColumn, null, null, null);
//                    cursor.moveToFirst();
//                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
//                    String picturePath = cursor.getString(columnIndex);  //获取照片路径
//                    cursor.close();
//                    if (!TextUtils.isEmpty(picturePath)) {
//                        cameraResult.onSuccess(picturePath);
//                    } else {
//                        cameraResult.onFail("文件没找到");
//                    }

                    Uri uriAblum1 = intent.getData();
                    cropImage(uriAblum1, photoURL);
                    break;
                //选择系统图库.裁剪
                case REQUEST_TAKE_PICTRUE_CROP_CODE:
                    Uri uriAblum = intent.getData();
                    onCropPic(uriAblum, photoURL);
//                  activity.startActivityForResult(takeCropPicture(photoURL, REQUEST_HEIGHT, REQUEST_WIDTH), REQUEST_TAKE_CROP_CODE);
                    break;
                //调用相机
                case REQUEST_TAKE_PHOTO_CODE:
//                    cameraResult.onSuccess(photoURL.getPath());
                    cropImage(photoURL, photoURL);
                    break;
                //调用相机,裁剪
                case REQUEST_TAKE_PHOTO_CROP_CODE:
                    onCropPic(photoURL, photoURL);
//                    activity.startActivityForResult(takeCropPicture(Uri.fromFile(new File(photoURL.getPath())), REQUEST_HEIGHT, REQUEST_WIDTH), REQUEST_TAKE_CROP_CODE);
                    break;
                //裁剪之后的回调
                case REQUEST_TAKE_CROP_CODE:
                    String path = getPic2Uri(photoURL, activity);
                    cameraResult.onSuccess(path);
                    break;
                case UCrop.REQUEST_CROP:
                    cameraResult.onSuccess(photoURL.toString());
                    break;
                default:
                    break;
            }
        }
    }

    public void cropImage(Uri uri, Uri outputUri) {
        new BitmapProcessTask(activity, uri, outputUri, resultWidth, resultHeight, new BitmapProcessTask.BitmapProcessCallback() {
            @Override
            public void onBitmapLoaded(Uri in, Uri out) {
                if (!isDestory)
                    cameraResult.onSuccess(photoURL.toString());
            }

            @Override
            public void onFailure(Exception bitmapWorkerException) {
                if (!isDestory)
                    cameraResult.onFail("fail");
            }
        }).execute();

    }

    boolean isDestory;

    public void onDestory() {
        isDestory = true;
    }


    public static String getPic2Uri(Uri contentUri, Context context) {
        try {
            Activity ac = (Activity) context;
            String[] proj = {MediaStore.Images.Media.DATA};
            Cursor cursor = ac.managedQuery(contentUri, proj, null, null, null);
            int column_index = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } catch (Exception e) {
            return contentUri.getPath();
        }
    }

    public interface PhotoResult {
        public void onSuccess(String path);

        public void onFail(String msg);

        public void onReupload();
    }

    public void uploadImage(AppActivity context, String filePath, Object tag, OnRequestListener uploadListener) {
        try {
            String file = FileUtil.encodeBase64File(filePath);
            RequestEntity<Map<String, String>> data = new RequestEntity<>();
            data.setCmd(com.epfresh.api.constant.AppRouterConstant.cmd_store_merchant_file_upload);
            Map<String, String> map = new HashMap<>();
            map.put("ext", "jpg");
            map.put("file", file);
            data.setParameters(map);

            context.request(data, tag, uploadListener);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
